//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


using System;
using System.Collections.Generic;
using System.Text;
using Shp.Runtime.Contract;

namespace Shp.Runtime.DataModel.Sql
{
    public class OneJoinPerEntityViewStrategy : IViewStrategy
    {
        #region IViewStrategy Members

        public string BuildViewCommand(EntityField[] fields, Guid tenantId, string tenantAlias, string entityDefName)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(Constants.DB.CreateView, entityDefName, tenantAlias);
            foreach (EntityField item in fields)
            {
                if (item.IsShared)
                {
                    sb.AppendFormat("E.{0}, ", item.Name);
                }
            }
            sb.Remove(sb.Length - 2, 2);
            
            foreach (EntityField item in fields)
            {
                if (!item.IsShared)
                {
                    sb.AppendFormat(", MIN(CASE WHEN X.extensionRef = '{0}' THEN X.value END) AS {0}", item.Name);                    
                }
            }

            sb.Append(" FROM PositionSharedValue AS E LEFT OUTER JOIN PositionCustomValue AS X ON E.Id =  X.InstanceId ");
            sb.AppendFormat(" WHERE E.tenantId = '{0}' GROUP BY E.id, E.postedOn, E.code, E.title ", tenantId);           
           
            return sb.ToString();
        }

        #endregion
    }
}
